﻿using Basic.FormCollect;
using Basic.FormModel.DB;
using Basic.FormModel.Model;
using Basic.FormRemoteModel.Column.Model;
using Basic.FormRemoteModel.QueryColumn.Model;
using Basic.FormService.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;

namespace Basic.FormService.lmpl
{
    internal class PhyQueryColumnService : IPhyQueryColumnService
    {
        private readonly IQueryColumnCollect _Column;

        public PhyQueryColumnService ( IQueryColumnCollect column )
        {
            this._Column = column;
        }

        public long Add ( QueryColumnAdd add )
        {
            if ( add.ShowMode != FormRemoteModel.PhyColShowMode.Column )
            {
                add.DataType = FormRemoteModel.PhyTableDataType.NVarchar;
                add.ColLen = 50;
                add.IsNull = true;
            }
            return this._Column.Add(add);
        }


        public void Delete ( long id )
        {
            DBPhysicalQueryColumn db = this._Column.Get(id);
            this._Column.Delete(db);
        }

        public QueryColumnDto Get ( long id )
        {
            DBPhysicalQueryColumn db = this._Column.Get(id);
            return db.ConvertMap<DBPhysicalQueryColumn, QueryColumnDto>();
        }
        public bool Set ( long id, QueryColumnSet set )
        {
            DBPhysicalQueryColumn db = this._Column.Get(id);
            return this._Column.Set(db, set);
        }
        public bool SetSort ( QueryColSet set )
        {
            ColumnSort[] sorts = this._Column.GetSorts(set.TableId, set.GroupId);
            int index = sorts.FindIndex(c => c.Id == set.Id);
            if ( index == -1 )
            {
                return false;
            }
            ColumnSort sour = sorts[index];
            ColumnSort to;
            if ( set.IsNext )
            {
                index += 1;
                if ( index == sorts.Length )
                {
                    return false;
                }
                to = sorts[index];
            }
            else
            {
                index -= 1;
                if ( index == -1 )
                {
                    return false;
                }
                to = sorts[index];
            }
            int sort = to.Sort;
            to.Sort = sour.Sort;
            sour.Sort = sort;
            this._Column.SetSort(sour, to);
            return true;
        }
    }
}
